#!/bin/bash

# ===========================================
# Android 混淆构建脚本
# ===========================================

# 检查参数
BUILD_TYPE="release"
if [ "$1" = "debug" ]; then
    BUILD_TYPE="debug"
fi

echo "开始构建混淆版本 ($BUILD_TYPE)..."

# 清理之前的构建
echo "清理之前的构建..."
./gradlew clean

# 构建指定版本（启用混淆）
if [ "$BUILD_TYPE" = "debug" ]; then
    echo "构建Debug版本（启用混淆）..."
    ./gradlew assembleDebug
    APK_PATH="app/build/outputs/apk/debug/app-debug.apk"
    MAPPING_PATH="app/build/outputs/mapping/debug/mapping.txt"
else
    echo "构建Release版本（启用混淆）..."
    ./gradlew assembleRelease
    APK_PATH="app/build/outputs/apk/release/app-release.apk"
    MAPPING_PATH="app/build/outputs/mapping/release/mapping.txt"
fi

# 检查构建是否成功
if [ $? -eq 0 ]; then
    echo "✅ 构建成功！"
    echo "混淆后的APK位置: $APK_PATH"
    
    # 显示APK信息
    echo ""
    echo "APK信息:"
    ls -lh "$APK_PATH"
    
    # 显示混淆映射文件位置
    echo ""
    echo "混淆映射文件位置: $MAPPING_PATH"
    
    # 如果存在映射文件，显示其大小
    if [ -f "$MAPPING_PATH" ]; then
        echo "映射文件大小:"
        ls -lh "$MAPPING_PATH"
    fi
    
    # 显示APK大小对比
    echo ""
    echo "APK大小分析:"
    if [ -f "$APK_PATH" ]; then
        APK_SIZE=$(stat -f%z "$APK_PATH" 2>/dev/null || stat -c%s "$APK_PATH" 2>/dev/null)
        APK_SIZE_MB=$((APK_SIZE / 1024 / 1024))
        echo "APK大小: ${APK_SIZE_MB}MB (${APK_SIZE} bytes)"
    fi
    
else
    echo "❌ 构建失败！"
    exit 1
fi

echo ""
echo "构建完成！"
echo ""
echo "使用方法:"
echo "  ./build-release.sh        # 构建Release版本"
echo "  ./build-release.sh debug  # 构建Debug版本"
